package com.dongdongshop.listenMq;

import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.service.OrderItemService;
import com.dongdongshop.service.OrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

import java.util.Objects;

@RocketMQTransactionListener
public class OrderMqListener implements RocketMQLocalTransactionListener{

    @DubboReference
    private OrderItemService orderItemService;

    @Autowired
    private RedisTemplate redisTemplate;

    @DubboReference
    private OrderService orderService;

    @Override//执行本地事务的方法                                   用于mq回查         用于要写入的参数,并返回状态
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {

        //获取到消息的Id
        String messageId = message.getHeaders().getId().toString();

        try {
            TbOrderItem orderItem =(TbOrderItem)arg;
            orderItemService.updateAllOrderItem(orderItem.getOrderNum(),orderItem.getTradeNo());
            orderService.updateAllOrder(orderItem.getOrderNum(),orderItem.getTradeNo());
            //返回之前存入我们的message状态 1表示 半消息成功提交
            redisTemplate.boundValueOps(messageId).set("1");
            //执行成功  返回commit状态
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            redisTemplate.boundValueOps(messageId).set("2");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override//当发送mq半消息,mq进行回查的方法,当我们未接受到返回的状态(成功或回滚),那就执行这个方法
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //获取到消息的Id
        String messageId = message.getHeaders().getId().toString();
        //获取redis中的半消息状态
        String status = (String) redisTemplate.boundValueOps(messageId).get();
        if (Objects.equals(status,"1")){  //如果查到了 说明我们的半消息已经提交过了,并且没有问题
            return RocketMQLocalTransactionState.COMMIT;
        }else if(Objects.equals(status,"2")){ //如果查到这个了,说明半消息提交失败.
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //如果没有,那我们就返回 Unknown
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
